import React, {Component} from 'react';
import AccountTab from './account.js';
import {ethers} from 'ethers';
import Transaction from "./transaction";
import WalletTools from "../servises/service.js"
import SettingTab from "./setting";
import account from "./account.js";
const Web3 = require('web3');


// import PubSub from "pubsub-js";
// import {Container} from "semantic-ui-react";

//本地以太坊环境
const network = "http://127.0.0.1:8545/"


class WalletTab extends Component {

    constructor(props) {
        super(props)
        this.state = {
            wallet: props.wallet,
            address: '',
            txCount: 0,
            balance: 0,
            walletPointer:"",
            selectWalletId : 0

        }
    }


    componentDidMount() {
        if (this.state.wallet.isMetaMask){
            this.connectMetaMask()
        }else {
            this.update()
        }

    }

    //非metamask网络连接
    update = async () => {

        let provider = new ethers.providers.JsonRpcProvider(network)
        let walletPointer = this.state.wallet.connect(provider)
        console.log("wallet:", walletPointer)

        //获取余额
        let balance = await walletPointer.getBalance()
        balance = ethers.utils.formatEther(balance)
        let address = await walletPointer.getAddress()

        let txCount = await walletPointer.getTransactionCount()
        console.log("准备使用setState方法")

        this.setState({balance, address, txCount,walletPointer}, () => {console.log("使用setState方法完毕")}
    )


}
    //连接metamask
    connectMetaMask = async () => {

        if (typeof window.ethereum !== 'undefined') {
            console.log('MetaMask is installed!');
        }
        let accounts = await window.ethereum.request({ method: 'eth_accounts' });
        console.log(accounts)
        this.setState({account:accounts[0]})

    }

onSendClick = async (txTo,txValue)=>{
    //检查转账地址是否有效
    if (!WalletTools.checkAddress(txTo)){
        alert("转账地址无效")
        return
    }
    //检查转账金额是否为数字
    if(isNaN(txValue)){
        alert("不是一个有效数字")
        return
    }

    txValue = ethers.utils.parseEther(txValue);
    console.log("txValue", txValue);

    if (this.state.wallet.isMetaMask){

    }else {
        try {
            let wallet = this.state.walletPointer;

            console.log("当前转账钱包为:", wallet);
            let res = await wallet.sendTransaction({
                to: txTo,
                value: txValue
            });
            console.log("转账结果详情:", res);

            alert(`转账成功!`);
            this.update()
        } catch (error) {
            alert(`转账失败!!`);
            console.log(error);
        }
    }





}


render() {
 return (
     <div>
         <AccountTab allInfo={this.state}/>
         <Transaction onSendClick = {this.onSendClick}/>
         <SettingTab walletPointer={this.state.walletPointer}/>

     </div>

 )
}
}


// module.exports =  walletTab

export default WalletTab;